import psutil

def top_cpu_processes(n=10):
    # 获取所有进程
    procs = []
    for p in psutil.process_iter(['pid', 'name', 'cpu_percent']):
        try:
            # cpu_percent 需要先调用一次，间隔后才能获得准确值
            p.cpu_percent(interval=None)
            procs.append(p)
        except (psutil.NoSuchProcess, psutil.AccessDenied):
            pass

    # 休眠1秒，给 cpu_percent 采样时间
    psutil.cpu_percent(interval=1)

    # 重新获取 cpu_percent，更新数据
    for p in procs:
        try:
            p.cpu = p.cpu_percent(interval=None)
        except (psutil.NoSuchProcess, psutil.AccessDenied):
            p.cpu = 0

    # 根据 cpu 占用排序，取前 n 个
    top = sorted(procs, key=lambda p: p.cpu, reverse=True)[:n]

    # 返回进程信息
    result = []
    for p in top:
        try:
            result.append({
                'pid': p.pid,
                'name': p.name(),
                'cpu_percent': p.cpu,
            })
        except (psutil.NoSuchProcess, psutil.AccessDenied):
            continue
    return result

if __name__ == '__main__':
    for proc in top_cpu_processes(10):
        print(f"PID: {proc['pid']}, Name: {proc['name']}, CPU%: {proc['cpu_percent']}")
